<template>
  <div id="Statistics">
    <div class="content">
      <div class="overflow-auto">
        <div class="Statistics_body">
          <div class="StatisticsData">

            <!-- 筛选时间 -->
            <div class="screen_datepicker screen_datepicker_action">
              <el-date-picker size="small" style="width: 320px;" v-model="screenDate" type="daterange" range-separator="至"
                @change="screenDateChange" start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd">
              </el-date-picker>
              <i class="el-icon-date"></i> <!-- 替换为你的图标 -->
            </div>
            <!-- END筛选时间 -->
            <!-- 营业额概况 -->
            <div class="turnover">
              <p>营业额概况<span>统计说明</span></p>
              <el-row class="generalize" :gutter="30">
                <el-col :xs="24" :sm="6" :md="6" :lg="6" :xl="6">
                  <div class="sum">
                    <div style="padding: 15px;">
                      <div class="sumName">总营业额(元)</div>
                      <div class="price">￥{{ basicsData.total_sales }}</div>
                      <div>日环比 <span> 0% </span> </div>
                    </div>
                  </div>
                </el-col>
                <el-col :xs="24" :sm="18" :md="18" :lg="18" :xl="18">
                  <el-row :gutter="20" class="other">
                    <el-col :xs="24" :sm="8" :md="8" :lg="8" :xl="8">
                      <div class="sum">
                        <div style="padding: 15px;">
                          <div class="sumName">房费(元)</div>
                          <div class="price">￥{{ basicsData.room_fee_total }}</div>
                          <div>日环比 {{ basicsData.room_fee_percent }}</div>
                        </div>
                      </div>
                    </el-col>
                    <el-col :xs="24" :sm="8" :md="8" :lg="8" :xl="8">
                      <div class="sum">
                        <div style="padding: 15px;">
                          <div class="sumName">违约金(元)</div>
                          <div class="price">￥{{ basicsData.penal_total }}</div>
                          <div>日环比 {{ basicsData.penal_percent }}</div>
                        </div>
                      </div>
                    </el-col>
                    <el-col :xs="24" :sm="8" :md="8" :lg="8" :xl="8">
                      <div class="sum">
                        <div style="padding: 15px;">
                          <div class="sumName">客房消费(元)</div>
                          <div class="price">￥{{ basicsData.consume_total }}</div>
                          <div>日环比 {{ basicsData.consume_percent }}</div>
                        </div>
                      </div>
                    </el-col>
                  </el-row>
                </el-col>
              </el-row>
            </div>
            <!-- END营业额概况 -->
            <el-row class="charts" :gutter="30">
              <el-col :xs="24" :sm="24" :md="24" :lg="8" :xl="8">
                <div class="charts_Doughnut">
                  <div class="title">营业汇总统计</div>
                  <div id="Doughnut"></div>
                </div>
              </el-col>
              <el-col :xs="24" :sm="24" :md="24" :lg="16" :xl="16">
                <div class="charts_Line">
                  <div class="title">每日营业统计</div>
                  <div class="charts_Line_bottom">
                    <div class="radio">
                      <el-radio-group v-model="radio1" size="small" @change="radio1Change">
                        <el-radio-button label="违约金"></el-radio-button>
                        <el-radio-button label="消息中心"></el-radio-button>
                        <el-radio-button label="角色管理"></el-radio-button>
                        <el-radio-button label="定时任务补偿"></el-radio-button>
                      </el-radio-group>
                    </div>
                    <div id="Line"></div>
                  </div>
                </div>
              </el-col>
            </el-row>

            <!-- 营业明细 -->
            <div class="detail">
              <div class="detail_top">
                <div class="title">
                  营业明细
                  <span>({{ screenDate[0] }} ~ {{ screenDate[1] }})</span>
                </div>
                <div>
                  <el-button type="primary" size="small" @click="openExport">导出报表</el-button>
                </div>
              </div>
              <div class="eltable">
                <el-table ref="exportTable" :data="tableData" style="width: 100%"
                  :header-cell-style="{ background: '#EBF1F6' }">
                  <el-table-column v-for="(item, index) in tableHeaderData" :key="index">
                    <template slot="header">
                      <div>{{ item }}</div>
                    </template>
                    <template slot-scope="scope">
                      <div>{{ scope.row[index] }}</div>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </div>

            <!-- 导出报表 -->
            <ExportTable now_export="营业汇总" :tableHeaders="tableHeaders" :tableScreen="tableScreen"
              :drawerVisible_Table="drawerVisible_Table" @update:drawerVisible_Table="handleDrawerVisible_Table">
            </ExportTable>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts'
// import { exportToExcel } from '../../../../api/export'
import ExportTable from '../../../../components/exportTable/exportTable.vue'
import { getdaysAgo } from '../../../../api/countDay'
export default {
  name: 'Statistics',
  components: {
    ExportTable
  },
  data() {
    return {
      // 导出报表组件
      drawerVisible_Table: false,
      tableHeaders: [],//表格的所有表头
      tableScreen: [],//表格筛选字段

      radio1: '违约金',//每日营业统计
      isScreenDate: false,//是否筛选了时间
      isScreenDateType: 0,//类型 1代表，用户选择的时间相同，0代表用户选择的时间不同
      screenDate: [getdaysAgo(new Date(), 1, true), getdaysAgo(new Date(), 1, true)],//筛选时间

      tableHeaderData: [],//营业明细表格
      tableData: [],//营业明细表格
      pieData: [],//圆环数据
      lineDates: [],//日期数组
      lineValues: [],//日期数组
      basicsData: {},//基础数据

      myChart_Doughnut: null,
      myChart_Line: null,
    }
  },
  created() {
    this.getTurnover()
  },
  mounted() {
    // 监听窗口大小变化
    window.addEventListener('resize', this.handleResize);
  },
  beforeDestroy() {
    // 移除窗口大小变化的监听
    window.removeEventListener('resize', this.handleResize);
  },
  methods: {
    /**
    * 导出明细按钮
    */
    openExport() {
      if (this.tableData.length == 0) {
        this.$message.warning('没有可导出的数据！')
        return
      }
      const tableHeaders = Array.from(this.$refs.exportTable.$el.querySelectorAll('th')).map(header => header.innerText).filter(item => item != '');

      const tableScreen = [
        ['开始时间', this.screenDate[0] ? this.screenDate[0] : '全部', this.screenDate[0]],
        ['结束时间', this.screenDate[1] ? this.screenDate[1] : '全部', this.screenDate[1]],
      ]
      console.log(tableHeaders, 'tableHeaders');
      console.log(tableScreen, 'tableScreen');
      this.tableHeaders = tableHeaders  // 报表字段
      this.tableScreen = tableScreen  // 筛选字段
      this.drawerVisible_Table = true;
    },
    // 更新父组件的抽屉状态 导出明细
    handleDrawerVisible_Table(value) {
      this.drawerVisible_Table = value;
    },

    // 导出表格
    // exportToExcel() {
    //   let table = this.$refs.exportTable.$el; // 获取表格节点
    //   exportToExcel(table)
    // },
    // 监听窗口大小变化
    handleResize() {
      window.onresize = () => {
        this.myChart_Doughnut.resize(); // 环形图
        this.myChart_Line.resize(); // 折线图
      }
    },
    // 折线单选按钮改变事件
    radio1Change() {
      this.getLine()
    },
    // 筛选日期时间发生变化
    screenDateChange() {
      if (this.screenDate) {
        this.isScreenDate = true//代表已经筛选了时间  false时代表默认进来时获取的数据日期为当前日期
        if (this.screenDate[0] == this.screenDate[1]) {
          this.isScreenDateType = 1//选择时间相同，则获取该日期前七天的日期作为明细的开始时间
        } else {
          this.isScreenDateType = 0
        }
      }
      console.log(this.screenDate, 'screenDate');
      this.getTurnover()
    },

    //环形图表
    DoughnutChart() {
      let chartDom = document.getElementById('Doughnut')
      chartDom.removeAttribute('_echarts_instance_');

      this.myChart_Doughnut = echarts.init(chartDom)
      let option
      option = {
        tooltip: {
          trigger: 'none',
          // trigger: 'item',
          // formatter: function (params) {
          //   return params.name + ': ' + (parseFloat(params.value) * 100).toFixed(2) + '%';
          // }
        },
        legend: {
          top: '10%',
          left: 'left',
          orient: 'vertical',   // 设置纵向排列显示
        },
        graphic: {
          type: 'text',
          left: 'center',
          top: 'middle',
          style: {
            text: `总收款(元）\n ${this.basicsData.total_sales} `,
            textAlign: 'center',
            fontSize: 18,
            fontWeight: 'bold'
          }
        },
        series: [
          {
            name: '营业汇总统计',
            type: 'pie',
            radius: ['40%', '70%'],
            avoidLabelOverlap: false,
            label: {
              show: false // 隐藏标签
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '20',
                fontWeight: 'bold',
                formatter: function (params) {
                  return params.name + ': ' + (parseFloat(params.value) * 100).toFixed(2) + '%';
                }
                // formatter: '{b}: {c}' // 显示数据项名称和值
              }
            },
            labelLine: {
              show: false
            },
            data: this.pieData
          }
        ]
      }
      option && this.myChart_Doughnut.setOption(option)

      // window.onresize = function () {
      //   this.myChart_Doughnut.resize();
      // }

    },



    LineChart() {
      // 折线
      let LineDom = document.getElementById('Line')
      LineDom.removeAttribute('_echarts_instance_');

      this.myChart_Line = echarts.init(LineDom)
      let option_Line

      option_Line = {
        tooltip: {
          trigger: 'axis'
        },
        xAxis: {
          type: 'category',
          data: this.lineDates,
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            data: this.lineValues,
            type: 'line',
            smooth: true
          }
        ]
      }

      option_Line && this.myChart_Line.setOption(option_Line)
      // window.onresize = function () {
      //   myChart_Doughnut.resize();//环形图
      //   this.myChart_Line.resize();//折线图
      // }
    },


    // 获取折线数据
    getLine() {
      // 折线数据图片  
      let lineData = {
        hotel_id: sessionStorage.getItem('hotel_id'),
        start_date: this.isScreenDate == false ? getdaysAgo(new Date(), 7, true) : this.isScreenDateType == 1 ? getdaysAgo(this.screenDate[0], 7, true) : this.screenDate[0],
        end_date: this.isScreenDate == false ? getdaysAgo(new Date(), 0) : this.screenDate[1],
        type: 1,//1住房总营业额 2 违约金 3 客房消费 4 房费
      }
      this.my_request('supplier/statistics/turnover-line', lineData, "GET").then(res => {
        console.log(res, '折线数据');
        let { code, data } = res.data
        if (code === 200) {
          this.lineDates = data.dates
          this.lineValues = data.values
          this.LineChart()
        }
      })
    },

    // 营业汇总基础数据   环形图+基础数据
    getTurnover() {
      // 营业汇总基础数据   环形图+基础数据
      let basicData = {
        hotel_id: sessionStorage.getItem('hotel_id'),
        start_date: this.screenDate[0],
        end_date: this.screenDate[1]
      }
      this.my_request('supplier/statistics/turnover-basic', basicData, "GET").then(res => {
        // console.log(res, '营业汇总基础数据');
        let { code, data } = res.data
        if (200 == code) {
          this.pieData = data.pie.map(item => {
            item.value = (parseFloat(item.value) / 100);
            return item
          })
          this.basicsData = data.basics
          this.DoughnutChart()
        }
      })
      // 营业汇总明细 表格数据
      this.my_request('supplier/statistics/turnover-detail', basicData, "GET").then(res => {
        console.log(res, '营业汇总明细');
        let { code, data } = res.data
        if (code === 200) {
          this.tableData = data.data
          this.tableHeaderData = data.header
        }
      })

      // 获取折线数据
      this.getLine()
    },
  }
}
</script>


<style lang="scss" scoped>
.eltable {
  border: 1px solid #E4E7ED;
}

.content {
  .overflow-auto {
    width: calc(100vw - 190px);
    height: calc(100vh - 100px);
    overflow: auto;
    padding: 20px;

    .Statistics_body {
      width: 100%;

      .turnover {
        margin: 20px 0 10px 0;

        p {
          padding-bottom: 20px;
          font-size: 16px;

          span {
            color: #999999;
            margin-left: 10px;
            font-size: 12px;
          }
        }

        .generalize {
          // height: 120px;

          .sum {
            width: 100%;
            height: 100px;
            border-radius: 2px;
            box-shadow: 0px 4px 7px rgba(222, 222, 222, 0.5);
            background-color: #ffffff;

            .sumName {
              width: 100%;
              overflow: hidden;
              white-space: nowrap;
              text-overflow: ellipsis;
            }

            div:nth-child(2) {
              font-size: 24px;
            }

            div:nth-child(3) {
              font-size: 12px;
              color: #999999;

              span {
                color: red;
              }
            }
          }

          .other {
            background: #ffffff;
            border-radius: 2px;
            box-shadow: 0px 4px 7px rgba(222, 222, 222, 0.5);
            margin: 0px !important;

            .sum {
              box-shadow: none !important;
              overflow: hidden;
            }
          }

        }
      }

      .charts {
        // height: 350px;

        .title {
          height: 50px;
          line-height: 50px;
        }

        .charts_Doughnut {
          // width: 35%;

          #Doughnut {
            width: 100%;
            height: 300px;
            background-color: #ffffff;
          }
        }

        .charts_Line {
          // width: calc(65% - 0px);
          height: 350px;

          .charts_Line_bottom {
            width: calc(100% - 40px);
            padding: 20px;
            height: 260px;
            background-color: #ffffff;

          }

          .radio {
            height: 32px;
          }

          #Line {
            width: 100%;
            height: calc(260px - 32px);
          }
        }
      }

      .detail {
        padding-bottom: 30px;

        .detail_top {
          display: flex;
          justify-content: space-between;
          padding: 20px 0;

          .title {
            span {
              margin-left: 20px;
              color: #999999;
              font-size: 13px;
            }
          }

        }
      }

    }
  }
}

::v-deep .el-table__header-wrapper {
  background-color: #f6f8ff;
}
</style>
<!-- 日期选择器样式 -->
<style lang="scss" scoped>
.screen_datepicker_action {
  ::v-deep .el-input__inner::before {
    content: '筛选时间';
    position: absolute;
    left: 0px;
    top: 50%;
    transform: translateY(-50%);
    width: 80px;
    text-align: center;
    color: #333333;
    font-size: 13px;
  }
}

::v-deep .el-input__icon.el-range__icon.el-icon-date {
  display: none;
}

::v-deep .el-date-editor.el-range-editor.el-input__inner.el-date-editor--daterange.el-range-editor--small {
  padding-left: 70px;
}

.screen_datepicker {
  position: relative;
  width: 320px;
  height: 32px;
}

.screen_datepicker i {
  position: absolute;
  right: 5px;
  z-index: 7;
  color: black;
  line-height: 32px;
}
</style>